package org.hot100_0.leetcode25;

import org.leetcode.easy.ListNode;

public class Solution {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6)))));

        ListNode reversedList = reverseKGroup(head, 2);

        printListNode(reversedList);
    }

    public static void printListNode(ListNode head) {

        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }

    }

    public static ListNode reverseKGroup(ListNode head, int k) {

        int size = 0;

        ListNode temp = head;

        while (temp != null) {
            temp = temp.next;
            size++;
        }

        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode preGroupEnd = dummy;

        ListNode pre = null;
        ListNode next = null;

        for (int i = size; i >= k; i = i - k) {

            int tempK = k;

            ListNode currGroupEnd = preGroupEnd.next;

            while (tempK > 0) {
                next = head.next;
                head.next = pre;
                pre = head;
                head = next;
                tempK--;
            }

            preGroupEnd.next = pre;

            currGroupEnd.next = head;

            preGroupEnd = currGroupEnd;

        }

        return dummy.next;
    }

}
